//
//  DDMoneyDetailViewController.m
//  DingDongZP
//
//  Created by 杨政涛 on 16/10/14.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

#import "DDMoneyDetailViewController.h"
#import "DDTitlePullView.h"
#import "DDMoneyDetailTableViewCell.h"

#import "DDMoneybagHomepageService.h"

#import "DDMoneybagDetailModel.h"

@interface DDMoneyDetailViewController ()


@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) NSString *titleString;
@property (strong, nonatomic) DDTitlePullView *pullView;

@property(nonatomic,strong)DDMoneybagHomepageService *moneybagHomepageService;

@property(nonatomic,strong)DDMoneybagDetailModel *moneybagDetail;

@property(nonatomic,strong)NSArray *listCout;  //每次请求的数据

@property(nonatomic,strong)NSMutableArray *AllList;  //上拉加载更多增加的数据

@property(nonatomic,strong)NSString *hase_nextpage; // 是否有下一页 1有 0 无

@property(nonatomic,assign)NSInteger recordPage; // 记录上拉加载page页数

@property(nonatomic,strong)NSString *recordType; // 是否有下一页 1有 0 无


@end

@implementation DDMoneyDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [self.rdv_tabBarController setTabBarHidden:true animated:true];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setNavgationBarTitleWithArray:@[@"全部",@"支出",@"收入"]];
    
    self.AllList = [NSMutableArray array];
    
    self.moneybagHomepageService = [[DDMoneybagHomepageService alloc]init];

    self.recordType = @"";
    
    [self setupDataWithPage:self.recordPage withType:self.recordType];
    
    [self configureTableView];
}


#pragma mark - TitleView

- (void)setNavgationBarTitleWithArray:(NSArray *)titleArray
{
    
    self.titleString = @"收支明细";
    
    self.pullView = [[DDTitlePullView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 -49)];
    self.pullView.hidden = YES;
    self.pullView.titles = [NSArray arrayWithArray:titleArray];
    [self.view addSubview:_pullView];
    
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.frame = CGRectMake(0, 0, 180, 30);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.attributedText = [self setTitleAttributed];
    self.titleLabel.userInteractionEnabled = YES;
    self.navigationItem.titleView = self.titleLabel;
    
    WEAKSELF
    self.pullView.seletedTitleBlock = ^(NSInteger idx) {
        
        if (idx == 0) {
            
          weakSelf.titleString = @"收支明细";
          weakSelf.recordType = @"";  // 默认显示全部收支明细

        }else{
           
          weakSelf.titleString = [NSString stringWithFormat:@"%@明细",titleArray[idx]];
            
            if (idx == 1) {
                
                // 支出   type = -1
                weakSelf.recordType = @"-1";  // 默认显示全部收支明细
            }
            
            if (idx == 2) {
                
                // 收入   type = 1
                weakSelf.recordType = @"1";  // 默认显示全部收支明细
            }
        }

        weakSelf.titleLabel.attributedText = [weakSelf setTitleAttributed];
   
        /**
         *  切换数据后  AllList 清空  recordPage = 0  然后进行网络请求
         */
        [weakSelf beginRefreshHeader];
    };
    
    [self.titleLabel bk_whenTapped:^{
        
        if (![weakSelf.pullView isShowPullView]) {
            
            [weakSelf.pullView showPullView];
        } else {
            
            [weakSelf.pullView dismissPullView];
        }
        weakSelf.titleLabel.attributedText = [weakSelf setTitleAttributed];
        
    }];
    
}

- (void)configureTableView
{
    self.tableView.rowHeight = 65;
    WEAKSELF
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(weakSelf.view);
        make.left.mas_equalTo(weakSelf.view);
        make.right.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view);
    }];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self addRefreshHeader];
        [self addRefreshFooter];
}

#pragma mark  UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.AllList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    DDMoneyDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"moneyDetail"];
    if (cell == nil) {
        
        cell = [[DDMoneyDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"moneyDetail"];
    }
    
    self.moneybagDetail = [DDMoneybagDetailModel yy_modelWithJSON:self.AllList[indexPath.row]];
    cell.dataModel = self.moneybagDetail;

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return TableViewSectionHeight;
}

/**
 *  网络请求
 *
 *  @param page 可选参数，默认到底自动加载，当返回空数据即没有更多数据了，每页20条数据，页码从0开始
 *  @param type 默认全部，1收入 －1支出
 */
- (void)setupDataWithPage:(NSInteger)page withType:(NSString *)type
{
    
    WEAKSELF
    [self.moneybagHomepageService queryMoneybagDetailWithPage:page withType:type SuccessBlock:^(id responseObject) {
                
        [weakSelf endRefreshHeader];
        [weakSelf endRefreshFooter];
                
        self.hase_nextpage =responseObject[@"data"][@"hase_nextpage"];
        self.listCout = responseObject[@"data"][@"list"];
        [self.AllList addObjectsFromArray:self.listCout];
        
        [self performSelectorOnMainThread:@selector(backToMainToUpdata) withObject:self waitUntilDone:YES];
    } failBlock:^(id responseObject, NSError *error) {
        
        [weakSelf endRefreshHeader];
        [weakSelf endRefreshFooter];
        [weakSelf requestFaild];
    }];

}

- (void)backToMainToUpdata
{
    
    WEAKSELF
    if ([self.hase_nextpage isEqualToString:@"0"]) {
        
        [weakSelf  setFooterHidden:true];
    } else {

        [weakSelf  setFooterHidden:false];
    }
    
    [self.tableView reloadData];
}

// 头部下拉刷新
- (void)loadNewData
{
   
    self.AllList = [NSMutableArray array];
    self.recordPage = 0;
    [self setupDataWithPage:self.recordPage withType:self.recordType];
}

//尾部上拉加载数据
- (void)loadMoreData
{
    self.recordPage++;
    
    [self setupDataWithPage:self.recordPage withType:self.recordType];
}


- (void)viewWillDisappear:(BOOL)animated
{

    [self.rdv_tabBarController setTabBarHidden:false animated:true];
    
    if (!self.pullView.hidden && self.pullView.isShowPullView) {
        [self.pullView dismissPullView];
        self.titleLabel.attributedText = [self setTitleAttributed];
    }
}

- (NSMutableAttributedString *)setTitleAttributed
{
    NSMutableAttributedString *titleAttributed = [[NSMutableAttributedString alloc] initWithString:self.titleString];
    [titleAttributed addAttribute:NSForegroundColorAttributeName
                            value:[UIColor whiteColor]
                            range:NSMakeRange(0,self.titleString.length)];
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    if ([self.pullView isShowPullView]) {
        textAttachment.image = [UIImage imageNamed:@"pull_up"];
    } else {
        textAttachment.image = [UIImage imageNamed:@"pull_down"];
    }
    
    textAttachment.bounds = CGRectMake(5, 2, 9, 5);
    [titleAttributed insertAttributedString:[NSAttributedString attributedStringWithAttachment:textAttachment] atIndex:self.titleString.length];
    return titleAttributed;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
